from typing import List, Dict, Any
import requests
import logging

# 配置日志
logger = logging.getLogger(__name__)

class Agent:
    def __init__(self, name: str, instructions: str, model: str = "glm-4-plus"):
        self.name = name
        self.instructions = instructions
        self.model = model
        self.base_url = "http://180.184.65.98:38880/atomgit"
        logger.info(f"初始化智能体: {name}")

    def run(self, messages: List[Dict[str, str]]) -> Dict[str, Any]:
        """运行代理并返回结果"""
        try:
            # 构建提示词
            prompt = self._build_prompt(messages)
            logger.debug(f"构建的提示词: {prompt[:200]}...")
            
            # 调用模型API
            response = self._call_model_api(prompt)
            
            return {
                "messages": messages + [{"role": "assistant", "content": response}],
                "result": response
            }
        except Exception as e:
            logger.error(f"Agent {self.name} 执行失败: {str(e)}")
            raise Exception(f"Agent执行失败: {str(e)}")

    def _build_prompt(self, messages: List[Dict[str, str]]) -> str:
        """构建提示词"""
        prompt = f"Instructions: {self.instructions}\n\n"
        for message in messages:
            prompt += f"{message['role'].capitalize()}: {message['content']}\n"
        return prompt

    def _call_model_api(self, prompt: str) -> str:
        """调用模型API"""
        try:
            logger.debug(f"调用API，提示词长度: {len(prompt)}")
            # 模拟返回，因为实际API endpoint还未实现
            mock_response = f"Generated content based on prompt: {prompt[:100]}..."
            
            # TODO: 当API准备好后，替换为实际的API调用
            # response = requests.post(f"{self.base_url}/generate", json={
            #     "prompt": prompt,
            #     "model": self.model,
            #     "max_length": 2000,
            #     "temperature": 0.7
            # })
            # if response.status_code == 200:
            #     return response.json()["generated_text"]
            
            return mock_response
            
        except Exception as e:
            logger.error(f"模型调用失败: {str(e)}")
            return f"基于提示词 '{prompt[:100]}...' 的生成内容"
